// pages/communicate/publish/publich.js
var app=getApp()
const dbquestions = wx.cloud.database().collection("questions")
const dbarticle = wx.cloud.database().collection("article")
const user=wx.getStorageSync('user')
var util=require('../../../utils/utils')
Page({
    data: {
        title:"",
        content:"",
        haveImage:false,
        url:"",
        // 问题是1 文章是0
        type:""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // wx.getStorageSync('user')
    },
    
//   题目文本
  titleInput(e){
    this.setData({
        title:e.detail.value
    })
},
//   内容文本
contentText(e){
  this.setData({
      content:e.detail.value
  })
},
// 查看大图(暂未成功！)
handleImagePreview(res){
    // const imageurl = this.data.imageurl
    // wx.previewImage({
    //   urls: imageurl, //要预览的图片
    // })
    // const imageurl = this.data.url
    let currentUrl = res.currentTarget.dataset.src
    console.log(res);
    wx.previewImage({
    //     current:imageurl,
    //   urls: imageurl, //要预览的图片
        current: currentUrl,
        urls:[currentUrl]
    })
},
//长按删除
DeleteImg: function (e) {
    let that = this;
    let imageurl = that.data.url;
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          //console.log('点击确定了');
          that.setData({
            haveImage:false,
            url:""
          })
          imageurl.splice(index, 1);
        } else if (res.cancel) {
          //console.log('点击取消了');
          return false;
        }
        that.setData({
         url: imageurl
        });
      }
    })
  },
//   选择类型
radioChange(e){
    var that=this
    if(e.detail.value==="article"){
        console.log("文章");
        that.setData({
            type:0
        })
    }else{
        console.log("问题");
        that.setData({
            type:1
        })
    }
},
//   上传照片
    chooseimage(){
        var that = this;
        wx.chooseImage({
        count: 1, 
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        success: function (res) {
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            that.setData({
            haveImage:true,
            url:res.tempFilePaths[0]
            })
            //  console.log(res.tempFilePaths[0]);
            that.uploadImage(res.tempFilePaths[0])
           
        }
        })
    },
    // 上传到云开发的存储中
    uploadImage(fileURL){
        var that = this
        wx.cloud.uploadFile({
        cloudPath:new Date().getTime()+'.png', // 上传至云端的路径
        filePath: fileURL, // 小程序临时文件路径
        success: res => {
            // wx.showToast({
            //     title: '上传图片成功',
            // })
            if (res.fileID) {
                that.setData({
                //    haveImage:true,
                   url: res.fileID
                })
            }
            //获取图片的http路径
            // that.addImagePath(res.fileID)
        },
        fail: console.error
        })
    },
    // 加入数据库
  addData() {
      var that=this
      var time=util.formatTime(new Date())
     if(that.data.type==="questions"){
        dbquestions.add({
            data: {
            type:that.data.type,
              createdOn:time,
              nickname:user.nickName,
              images: that.data.url,
              content:that.data.content,
              title:that.data.title,
              haveimage:that.data.haveImage,
              usertype:user.userType,
              avatarurl:user.avatarUrl,
              isLike:false,
              peopleLike:0,
              answersCount:0
            },
            success(res) {
              console.log("添加成功", res),
              wx.showToast({
                  title: '发表成功！',
                })
              //    跳转页面 刷新
              wx.reLaunch({
              url: '/pages/communicate/index/index',
              })
            },
            fail() {
              console.log("添加失败", res)
              wx.showToast({
                  icon: 'none',
                  title: '发表失败'
                })
            }
          })
     }else{
        dbarticle.add({
            data: {
             type:that.data.type,
              createdOn:time,
              nickname:user.nickName,
              images: that.data.url,
              content:that.data.content,
              title:that.data.title,
              haveimage:that.data.haveImage,
              usertype:user.userType,
              avatarurl:user.avatarUrl,
              isLike:false,
              peopleLike:0,
              answersCount:0,
              eyes:0
            },
            success(res) {
              console.log("添加成功", res),
              wx.showToast({
                  title: '发表成功！',
                })
              //    跳转页面 刷新
              wx.reLaunch({
              url: '/pages/communicate/index/index',
              })
            },
            fail() {
              console.log("添加失败", res)
              wx.showToast({
                  icon: 'none',
                  title: '发表失败'
                })
            }
          })
     }
  },
    
    //   提交
    formSubmit(e) {
        var that=this
        if(that.data.title.length<3){
          wx.showToast({
            title: '标题少于3个字',
            icon:"none"
          })
          return false
        }
        if(that.data.content.length<5){
          wx.showToast({
            title: '内容少于5个字',
            icon:"none"
          })
          return false
        }
        if(that.data.type==""){
              wx.showToast({
                title: '请选择类型',
                icon:"none"
              })
              return false
            }
       wx.showLoading({
         title: '发布中',
       })
        this.addData()
        that.setData({
            title:"",
            content:"",
            haveImage:false,
            url:""
        })
         //   成功后跳转页面
        //   setTimeout(()=>{
        //     wx.redirectTo({
        //       url: '/pages/communicate/index/index.wxml',
        //     })
        //   },1000)
    }
})
